
#include <pthread.h>

#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libavcodec/opt.h"
#include "libavutil/pixdesc.h"
#include "libavdevice/avdevice.h"

#include "av_capture.h"
#include "av_encode.h"

static AVFormatContext *av_capture = NULL;

static void
av_capture_thread (void)
{
	AVPacket pkt;

	while (1) {
		if (av_read_packet(av_capture, &pkt) > 0) {
			av_encode_encode (&pkt);
			av_free_packet(&pkt);
		}
	}
}

int
av_capture_init (void)
{
	AVFormatParameters ap;
	AVInputFormat *fmt;
	pthread_t pid;
	int result = -1;

	fmt = av_find_input_format("video4linux2");

	memset (&ap, 0, sizeof (AVFormatParameters));
	ap.channel = 0;
	ap.width = 1280;
	ap.height = 720;
	ap.pix_fmt = PIX_FMT_YUV420P;

	if (av_open_input_file(&av_capture, "/dev/video0", fmt, 0, &ap) < 0) {
		fprintf(stderr, "av_open_input_file %s error..\n", "/dev/video0");
		goto err1;
	}
	if (pthread_create (&pid, NULL, (void *)av_capture_thread, NULL) != 0) {
		printf ("pthread_create av_capture_thread error!\n");
		goto err2;
	}
	return 0;
err2:
	av_close_input_file(av_capture);
err1:
	return result;
}
